package org.mozhu.zufang.system.auth.service;

import com.google.common.collect.Sets;
import org.apache.commons.collections.CollectionUtils;
import org.mozhu.zufang.system.auth.entity.UserAuth;
import org.mozhu.zufang.system.privilege.entity.Permission;
import org.mozhu.zufang.system.privilege.entity.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

@Service("userAuthAuthorityService")
public class UserAuthAuthorityService extends AbstractAuthorityService implements AuthorityService {

    @Autowired
    UserAuthServiceImpl userAuthService;

    @Override
    public Set<String> findStringRoles(Long userId) {
        UserAuth userAuth = userAuthService.findByUserId(userId);
        if (userAuth == null) {
            return Sets.newHashSet();
        }
        List<Role> roles = roleService.findAvailableRoles(userAuth.getRoleIds());
        return stringRoles(roles);
    }

    @Override
    public Set<String> findStringPermissions(Long userId) {
        UserAuth userAuth = userAuthService.findByUserId(userId);
        if (userAuth == null) {
            return Sets.newHashSet();
        }
        List<Role> roles = roleService.findAvailableRoles(userAuth.getRoleIds());
        Set<Long> permissionIds = rolesToPermissionIds(roles);

        if (CollectionUtils.isNotEmpty(userAuth.getPermissionIds())) {
            permissionIds.addAll(userAuth.getPermissionIds());
        }
        List<Permission> permissions = permissionService.findAvailablePermissions(permissionIds);
        return stringPermissions(permissions);
    }

}
